//
//  PKRequestManager.m
//  PianKe
//
//  Created by Li on 15/7/21.
//  Copyright (c) 2015年 Li. All rights reserved.
//

#import "PKRequestManager.h"

@interface PKRequestManager ()<NSURLConnectionDataDelegate>

@property (nonatomic, strong) NSMutableData *data;
//注释
@end

@implementation PKRequestManager

+ (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error{
    PKRequestManager *manager = [[PKRequestManager alloc] init];
    [manager manager:requestType requestWith:urlStr parDic:parDic finish:finish error:error];
}

- (void)manager:(RequestType)requestType requestWith:(NSString *)urlStr parDic:(NSDictionary *)parDic finish:(RequestFinish)finish error:(RequestError)error{
    self.requestFinish = finish;
    self.requestError = error;
    
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlStr]];
    //设置缓存策略(有缓存就用缓存，没有缓存就重新请求)
    request.cachePolicy = NSURLRequestReturnCacheDataElseLoad;
    
    if (requestType == POST) {
        [request setHTTPMethod:@"POST"];
        if (parDic) {
            [request setHTTPBody:[self dicToHTTPBody:parDic]];
        }
    }
    [NSURLConnection connectionWithRequest:request delegate:self];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
    _data = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
    [_data appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection{
    self.requestFinish(_data);
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
    self.requestError(error);
}

- (NSData *)dicToHTTPBody:(NSDictionary *)dic
{
    NSMutableString *dataStr = [NSMutableString string];
    for (NSString *key in dic)
    {
        NSString *str = [NSString stringWithFormat:@"&%@=%@", key, dic[key]];
        [dataStr appendString:str];
    }
    [dataStr deleteCharactersInRange:NSMakeRange(0, 1)];
    return [dataStr dataUsingEncoding:NSUTF8StringEncoding];
}


@end
